package authorization;

import java.io.PrintStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;


public class UserAuthorization
{
  private Connection connection;
  private Statement sentencia;
  private ResultSet rs;

  public UserAuthorization()
  {
//    try
//    {
//      Context initCtx = new InitialContext();
//      Context envCtx = (Context)initCtx.lookup("java:comp/env");
//	  DataSource ds = (DataSource)envCtx.lookup("jdbc/usersDB");
//	  this.con = ds.getConnection();
//	  String sql = "select * from users where username = ?";
//      this.stmt = this.con.prepareStatement(sql);
//    } catch (NamingException ne) {
//      disconnect();
//      System.err.println("AuthorizationWS in constructor: " + ne);
//    } catch (SQLException e) {
//      disconnect();
//      System.err.println("AuthorizationWS in constructor: " + e);
//      e.printStackTrace();
//    }
  }

  public User login(String username, String pass) throws InvalidUserException, InvalidPasswordException 
  {
	  User user = null;
	  try
	  {
		  Class.forName("org.sqlite.JDBC");
		  connection = java.sql.DriverManager.getConnection("jdbc:sqlite:/home/ander/workspace/ISOProject/WebServices/authorizationWS/db/users.db");//TODO FEDE
		
		  System.out.println ("Base de datos: nueva conexión."); // registro
			
		  sentencia = connection.createStatement();
		  String query = "SELECT * FROM users WHERE username = '" + username + "'";
		  //System.out.println(query);	
		  
		  rs = sentencia.executeQuery(query);
			
		  if (rs.next()) 
		  {
			  String password = rs.getString("password");
				
			  if (!pass.equals(password)) 
			  {
				  rs.close();
				  System.out.println("The password is not valid: " + pass);
				  throw new InvalidPasswordException("[InvalidPasswordException] The password is not valid");
			  }
				
			  user = new User(rs.getString("username"), rs.getString("password"), rs.getString("name"), rs.getInt("age"), rs.getString("sex"));
		  }
		  else
		  {
			  rs.close();
			  System.out.println("The user does not exist: " + username);
			  throw new InvalidUserException("[InvalidUserException] User with " + username + " does not exist in our database");
		  }
		  
		  disconnect();
	  } 
	  catch (ClassNotFoundException e)
	  {
		  e.printStackTrace();
	  } 
	  catch (SQLException e)
	  {
		  e.printStackTrace();
	  }
	  
	  System.out.println ("Base de datos: conexión cerrada."); // registro
	  
	  return user;
	  
//    User user = null;
//    try
//    {
//      this.stmt.setString(1, username);
//      this.rs = this.stmt.executeQuery();
//      if (this.rs.next()) {
//        String password = this.rs.getString("password");
//        if (!pass.equals(password)) {
//          this.rs.close();
//          System.out.println("The password is not valid: " + pass);
//          throw new InvalidPasswordException("[InvalidPasswordException] The password is not valid");
//        }
//        user = new User(this.rs.getString("username"), this.rs.getString("password"), this.rs.getString("name"), this.rs.getInt("age"), this.rs.getString("sex"));
//      }
//      else
//      {
//        this.rs.close();
//        System.out.println("The user does not exist: " + username);
//        throw new InvalidUserException("[InvalidUserException] User with " + username + " does not exist in our database");
//      }
//    }
//    catch (SQLException e) {
//      System.err.println("Authorization(): " + e);
//     e.printStackTrace();
//    }
//
//    System.out.println("Valid user - username: " + username + " or an SQL Exception !!!");
//    System.out.println("Greetings!: " + user == null ? "": user.getName());
//    return user;
	  
  }

  private void disconnect() 
  {
    try {
      this.sentencia.close();
      this.connection.close();
    } catch (Exception e) {
      System.err.println("Authorization.disconnect(): " + e);
    }
  }
}
